// Copyright 2007 the original author or authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package lichen.internal.services;

import java.util.List;

import lichen.entities.forum.Treeable;
import lichen.services.IMoveTreeNodeProcessor;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

/**
 * 向上移动
 * 
 * @author <a href="mailto:jun.tsai@bjmaxinfo.com">Jun Tsai</a>
 * @version $Revision: 111 $
 * @since 0.0.1
 */
class MoveUpProcessor extends AbstractMoveTreeNodeProcessor implements
		IMoveTreeNodeProcessor {
	private int moveBlockLeftStart = 0;

	private int moveBlockLeftEnd = Integer.MAX_VALUE;

	private int offset = 0;

	@Override
	protected void appendQueryReplaceNodeCriteria(DetachedCriteria criteria) {
		/*
		 * add restrictions:
		 * where left<self.left and left>parent.left order by left desc
		 */
		criteria.add(Restrictions.lt(Treeable.LEFT_PRO_NAME, getCurrentNode().getLeft()))
				.add(Restrictions.gt(Treeable.LEFT_PRO_NAME, getParentNode().getLeft()));
		criteria.addOrder(Order.desc(Treeable.LEFT_PRO_NAME));

	}

	@Override
	protected void fetchMoveBlockInfo(List list) {
		if (list.size() == 0) { // 未找到了移动的位置，说明已经溢出
			offset = getCurrentNode().getLeft()
					- (getParentNode().getLeft() + 1);
			moveBlockLeftStart = getParentNode().getLeft() + 1;
			moveBlockLeftEnd = getCurrentNode().getLeft() - 1;
		} else {// 找到了移动的位置
			Treeable replaceNode = (Treeable) list.get(0);
			offset = getCurrentNode().getLeft() - replaceNode.getLeft();
			moveBlockLeftStart = replaceNode.getLeft();
			moveBlockLeftEnd = getCurrentNode().getLeft() - 1;
		}

	}

	@Override
	protected int getMoveBlockLeftEnd() {
		return this.moveBlockLeftEnd;
	}

	@Override
	protected int getMoveBlockLeftStart() {
		return this.moveBlockLeftStart;
	}

	@Override
	protected int getOffset() {
		return 0 - this.offset;
	}

	@Override
	protected int getUpdateWidth() {
		return getCurrentNode().getRight() - getCurrentNode().getLeft() + 1;
	}

	@Override
	public Treeable constructRootNode() {
		Treeable rootNode = newTreeable();
		rootNode.setLeft(0);
		rootNode.setRight(Integer.MAX_VALUE);

		return rootNode;
	}

}
